<template>
    <div class="employee_container">
        <ZwSearchForm
            ref="searchRef"
            :key="searchType"
            row-num="4"
            :option="searchOption"
            :default-expand="false"
            @search="search"
            @reset="reset" />
        <ZwTable
            v-show="!isShowEmpty"
            ref="tableRef"
            :key="searchType"
            v-loading="loading"
            :loading="true"
            :close-loading="false"
            tab-h="500px"
            :select-all-group="true"
            select-all-radio
            :option="getTableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi"
            @select="onSelect"
            @select-all="onSelectAll"
            @select-all-total="selectAllTotal"
            @select-all-change="onSelectAllChange">
            <template #headerOperate>
                <el-button :loading="exportLoading" :disabled="!selectTableTotal" @click="handleExport">导出</el-button>
            </template>
        </ZwTable>
        <el-empty v-show="isShowEmpty" description="暂无数据" />
        <display-column-config-dialog v-model="columnConfigVisable" :type="columnType" @submit="handleSortSubmit" />
    </div>
</template>

<script setup lang="tsx">
import { computed, ref, reactive, watch } from 'vue';
import { ElTooltip } from 'element-plus';
import { QuestionFilled } from '@element-plus/icons-vue';
import ZwSearchForm from '@/components/zw/search-form1.0/SearchForm';
import ZwTable from '@/components/zw/table1.0/Table';
import { useRoute } from 'vue-router';
import { cloneDeep } from 'lodash';
import { timeSlotChange } from '@/utils/utils';

import { employeeColunms, productColunms, promotionLinkColunms } from '../configuration/searchOption';
import { employeeColumnOption, productColumnOption, promotionLinkColumnOption } from '../configuration/tableOption';

import DisplayColumnConfigDialog from '@/view/dataCenter/customerGroupAnalysis/customerGroupData/components/display-column-config-dialog.vue';

import { getGoodsList } from '@/api/ecommerce/dataStatistics';
import {
    getStaticsPromotionAccountDetail,
    getStaticsPromotionProductDetail,
    getStaticsPromotionUrlDetail,
    getCommonCustomFieldList,
    exportPromotionAccount,
    exportPromotionProduct,
    exportStaticsPromotionUrl
} from '@/api/ecommerce/dataStatistics';
import { getCreateList } from '@/api/common';

import { CUSTOM_LIST_TYPE, PROMOTION_METHOD_STATUS, PROMOTION_METHOD_TYPE } from '@/const/ecommerce';
import moreMenuSvg from '@/assets/dataCenter/moreMenu.svg';
import { parabolaAnimation } from '@/utils/parabola.js';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';

import { formatMoneyNoUnit } from '@/view/ecommerce/storeManage/list/storeDetail/components/PromotionStatistics/components/browse/render-column-number/utils.js';

import { createComponentName } from '@/components/zw/utils';

import { calendarChangefunc, disabledDateFunc, visibleChange } from '../../utils';

const [name, bem] = createComponentName('table');

const routers = useRoute();
// 店铺ID
const { shop_id } = routers.query;

// props： employee ｜ product ｜ promotionLink
const props = defineProps(['type']);

// ======================== 表单 of start ========================
const dateRender = () => {
    return (
        <div class="zw-search-form1__form-item-tooltip">
            <span>统计时间</span>
            <ElTooltip
                effect="dark"
                placement="top"
                content="查询商品以下各指标<br/>在此统计时间范围内<br/>的值"
                raw-content>
                <el-icon color="#ccc" size="16">
                    <QuestionFilled />
                </el-icon>
            </ElTooltip>
        </div>
    );
};

// 搜索项配置
const SEARCH_TYPE_OPTION = reactive({
    employee: {
        // 表格接口
        api: getStaticsPromotionAccountDetail,
        // 搜索表单的列
        column: [
            ...employeeColunms,
            {
                label: '推广商品',
                name: 'product_ids',
                value: [],
                type: 'selectV2',
                multiple: true,
                filterable: true,
                remote: true,
                placeholder: '请输入店铺商品名称选择',
                fetchOptionApi: (goods_info: any) => {
                    return new Promise(resolve => {
                        const params = {
                            goods_info,
                            shop_id,
                            page: 1,
                            page_size: Number.MAX_SAFE_INTEGER,
                            state: 'all'
                        };
                        getGoodsList(params).then((res: any) => {
                            const goodsArr: any[] = [];
                            res.data.forEach((goods: any) => {
                                goodsArr.push({
                                    ...goods,
                                    product_name:
                                        goods.state == 1 ? `${goods.product_name}（已下架）` : goods.product_name
                                });
                            });
                            resolve(goodsArr);
                        });
                    });
                },
                formatOption: (v: any) => ({
                    label: v.product_name,
                    value: v.id
                })
            },
            {
                label: '统计时间',
                name: 'date',
                default: [timeSlotChange('本周')[0], timeSlotChange('本周')[1]],
                type: 'datePicker',
                datePickerType: 'daterange',
                valueFormat: 'YYYY-MM-DD HH:mm:ss',
                format: 'YYYY-MM-DD HH:mm:ss',
                startPlaceholder: '开始日期',
                endPlaceholder: '结束日期',
                disabledDate: disabledDateFunc,
                render: dateRender,
                calendarChange: calendarChangefunc,
                visibleChange: visibleChange
            }
        ],
        // 表格的配置列
        tableOption: employeeColumnOption,
        // 默认值
        defaultParams: {
            shop_id, //店铺主键id
            start_date: timeSlotChange('本周')[0],
            end_date: timeSlotChange('本周')[1],
            promotion_type: [], //推广活动类型 1 淘口令
            promotion_way: [], //推广方式 1 企微私信 2企微群聊 3后台直接分享
            account_ids: [], //员工账号
            product_ids: [], //商品id
            page: 1,
            page_size: 15
        }
    },
    product: {
        // 表格接口
        api: getStaticsPromotionProductDetail,
        // 搜索表单的列
        column: [
            {
                label: '推广商品',
                name: 'product_ids',
                value: [],
                type: 'selectV2',
                multiple: true,
                filterable: true,
                remote: true,
                placeholder: '请输入店铺商品名称选择',
                fetchOptionApi: (goods_info: any) => {
                    return new Promise(resolve => {
                        const params = {
                            goods_info,
                            shop_id,
                            page: 1,
                            page_size: Number.MAX_SAFE_INTEGER,
                            state: 'all'
                        };
                        getGoodsList(params).then((res: any) => {
                            const goodsArr: any[] = [];
                            res.data.forEach((goods: any) => {
                                goodsArr.push({
                                    ...goods,
                                    product_name:
                                        goods.state == 1 ? `${goods.product_name}（已下架）` : goods.product_name
                                });
                            });
                            resolve(goodsArr);
                        });
                    });
                },
                formatOption: (v: any) => ({
                    label: v.product_name,
                    value: v.id
                })
            },
            ...productColunms,
            {
                label: '统计时间',
                name: 'date',
                default: [timeSlotChange('本周')[0], timeSlotChange('本周')[1]],
                type: 'datePicker',
                datePickerType: 'daterange',
                valueFormat: 'YYYY-MM-DD HH:mm:ss',
                format: 'YYYY-MM-DD HH:mm:ss',
                startPlaceholder: '开始日期',
                endPlaceholder: '结束日期',
                disabledDate: disabledDateFunc,
                render: dateRender,
                calendarChange: calendarChangefunc,
                visibleChange: visibleChange
            }
        ],
        // 表格的配置列
        tableOption: productColumnOption,
        // 默认值
        defaultParams: {
            shop_id, //店铺主键id
            start_date: timeSlotChange('本周')[0],
            end_date: timeSlotChange('本周')[1],
            promotion_type: [], //推广活动类型 1 淘口令
            promotion_way: [], //推广方式 1 企微私信 2企微群聊 3后台直接分享
            account_ids: [], //员工账号
            product_ids: [], //商品id
            page: 1,
            page_size: 15
        }
    },
    promotionLink: {
        // 表格接口
        api: getStaticsPromotionUrlDetail,
        // 搜索表单的列
        column: [
            {
                label: '推广内容',
                name: 'promotion_content',
                type: 'input',
                placeholder: '请输入推广内容，如：淘口令等'
            },
            {
                label: '推广商品',
                name: 'product_ids',
                value: [],
                type: 'selectV2',
                multiple: true,
                filterable: true,
                remote: true,
                placeholder: '请输入店铺商品名称选择',
                fetchOptionApi: (goods_info: any) => {
                    return new Promise((resolve, reject) => {
                        const params = {
                            goods_info,
                            shop_id,
                            page: 1,
                            page_size: Number.MAX_SAFE_INTEGER
                        };
                        getGoodsList(params)
                            .then((res: any) => {
                                const goodsArr: any[] = [];
                                res.data.forEach((goods: any) => {
                                    goodsArr.push({
                                        ...goods,
                                        product_name:
                                            goods.state == 1 ? `${goods.product_name}（已下架）` : goods.product_name
                                    });
                                });
                                resolve(goodsArr);
                            })
                            .catch(() => {
                                reject([]);
                            });
                    });
                },
                formatOption: (v: any) => ({
                    label: v.product_name,
                    value: v.id
                })
            },
            {
                label: '员工账号',
                name: 'account_ids',
                type: 'select',
                placeholder: '请选择子账号',
                clearable: true,
                multiple: true,
                fetchOptionApi: () => {
                    return new Promise(resolve => {
                        getCreateList({ noNeedLoading: true }).then(res => {
                            const arr = res.map((item: any) => {
                                item.value = item.id;
                                item.label = `${item.name}  (${item.phone}) `;
                                return item;
                            });
                            resolve(arr);
                        });
                    });
                }
            },
            {
                label: '统计时间',
                name: 'date',
                default: [timeSlotChange('本周')[0], timeSlotChange('本周')[1]],
                type: 'datePicker',
                datePickerType: 'daterange',
                valueFormat: 'YYYY-MM-DD HH:mm:ss',
                format: 'YYYY-MM-DD HH:mm:ss',
                startPlaceholder: '开始日期',
                endPlaceholder: '结束日期',
                disabledDate: disabledDateFunc,
                render: dateRender,
                calendarChange: calendarChangefunc,
                visibleChange: visibleChange
            },
            {
                label: '推广状态',
                type: 'select',
                name: 'promotion_status',
                placeholder: '请选择推广状态',
                fetchOptionApi: () => {
                    return new Promise(resolve => {
                        resolve(PROMOTION_METHOD_STATUS);
                    });
                }
            },
            {
                label: '推广方式',
                type: 'select',
                name: 'promotion_way',
                placeholder: '请选择推广方式',
                clearable: true,
                multiple: true,
                fetchOptionApi: () => {
                    return new Promise(resolve => {
                        resolve(PROMOTION_METHOD_TYPE);
                    });
                }
            }
        ],
        // 表格的配置列
        tableOption: promotionLinkColumnOption,
        // 默认值
        defaultParams: {
            shop_id, //店铺主键id
            start_date: timeSlotChange('本周')[0],
            end_date: timeSlotChange('本周')[1],
            promotion_type: [], //推广活动类型 1 淘口令
            promotion_way: [], //推广方式 1 企微私信 2企微群聊 3后台直接分享
            account_ids: [], //员工账号
            product_ids: [], //商品id
            page: 1,
            page_size: 15
        }
    }
});

// 搜索项类型：employee ｜ product ｜ promotionLink
const searchType = ref('promotionLink');
const searchRef = ref(null);

// 表格
const tableRef = ref(null);
const state = reactive({
    searchParams: cloneDeep(SEARCH_TYPE_OPTION[searchType.value].defaultParams)
});

/**
 * 搜索项列配置
 */
const searchOption = computed(() => {
    return SEARCH_TYPE_OPTION[searchType.value]?.column;
});

// 查询事件
const search = (v: any) => {
    tableRef.value?.clearSelection();
    tableRef.value?.clearAllSelect();
    const params = cloneDeep(SEARCH_TYPE_OPTION[searchType.value].defaultParams);
    /**
     * 处理日期和设置日期默认值
     * timeSlotChange('本周')[0], timeSlotChange('本周')[1]
     */
    if (params?.date) {
        params['start_date'] = params['date'][0];
        params['end_date'] = params['date'][1];
    } else {
        params['start_date'] = timeSlotChange('本周')[0];
        params['end_date'] = timeSlotChange('本周')[1];
    }
    if (v?.date) {
        params['start_date'] = v['date'][0];
        params['end_date'] = v['date'][1];
    } else {
        params['start_date'] = timeSlotChange('本周')[0];
        params['end_date'] = timeSlotChange('本周')[1];
        searchRef.value.state.form['date'] = [timeSlotChange('本周')[0], timeSlotChange('本周')[1]];
    }
    // 查询时去除首尾空格
    if (v?.promotion_content) {
        v['promotion_content'] = v?.promotion_content.trim();
    }
    state.searchParams = {
        ...params,
        ...v
    };
    delete state.searchParams?.date;
};

// 重置搜索项
const reset = (v: any) => {
    tableRef.value?.clearSelection();
    tableRef.value?.clearAllSelect();
    state.searchParams = {
        ...cloneDeep(SEARCH_TYPE_OPTION[searchType.value].defaultParams),
        ...v
    };
    delete state.searchParams?.date;
};

// ======================== 表单 of start ========================

/**
 * 切换时清掉所有的值，然后替换成默认的参数
 */
const handleTabChange = async () => {
    state.searchParams = cloneDeep(SEARCH_TYPE_OPTION[searchType.value].defaultParams);
    tableRef.value?.clearSelection();
    tableRef.value?.clearAllSelect();
};

// ======================== 表格 of start ========================

const isShowEmpty = ref(false);

// 表格加载中

const loading = ref(false);

// 导出按钮加载中
const exportLoading = ref(false);

const getRowKey = (row: any) => {
    return row.id;
};

// 自定义表头数据格式化
const withMapGetApiFun = fnApi => {
    return (params: any) => {
        // eslint-disable-next-line no-async-promise-executor
        return new Promise(async (resolve, reject) => {
            try {
                loading.value = true;
                const res = await fnApi(params);
                const { column, data } = res;
                // 遍历数值获取单位
                column.forEach((columnItem: any) => {
                    data.forEach((dataItem: any) => {
                        /**
                         * 推广内容列，空格替换为&nbsp;，解决 tootip 提示内容渲染后丢失空格问题
                         */
                        if (['promotion_content'].includes(columnItem.field_key)) {
                            dataItem[columnItem.field_key] = dataItem[columnItem.field_key].replace(/\s/g, '&nbsp;');
                        }
                        // 如果没有属性，不做操作
                        if (!dataItem.hasOwnProperty(columnItem.field_key)) {
                            return;
                        }
                        // 如果属性是金额字段，格式化数据
                        if (['crt_ord_amt', 'pay_ord_amt'].includes(columnItem.field_key)) {
                            if (['--', 0, '0'].includes(dataItem[columnItem.field_key])) {
                                return;
                            } else {
                                dataItem[columnItem.field_key] =
                                    dataItem[columnItem.field_key] !== ''
                                        ? `${formatMoneyNoUnit(dataItem[columnItem.field_key])}`
                                        : '--';
                            }
                        }
                    });
                });
                isShowEmpty.value = false;
                loading.value = false;
                resolve(res);
            } catch (err) {
                isShowEmpty.value = true;
                loading.value = false;
                reject(err);
            }
        });
    };
};

/** 查询接口的api */
const fetchApi = computed(() => {
    const apis = {
        promotionLink: withMapGetApiFun(SEARCH_TYPE_OPTION[searchType.value]?.api),
        employee: SEARCH_TYPE_OPTION[searchType.value]?.api,
        product: SEARCH_TYPE_OPTION[searchType.value]?.api
    };
    return apis[searchType.value];
});

// 表格列配置字段
const getTableOption = (columns: any[]) => {
    const tableOption = SEARCH_TYPE_OPTION[searchType.value]?.tableOption;

    if (!columns || !columns.length) {
        const arr = [];
        const obj = SEARCH_TYPE_OPTION[searchType.value]?.tableOption;
        const moneyKey = ['account_name', 'product_name'];
        for (const key in obj) {
            if (Object.hasOwnProperty.call(obj, key)) {
                let columnItemObj = {};
                // 金额和数量字段，格式化数据
                if (!moneyKey.includes(key)) {
                    columnItemObj = {
                        ...obj[key],
                        showOverflowTooltip: true,
                        render({ row }: any) {
                            return row[key] == '--' ? row[key] : formatMoneyNoUnit(row[key]);
                        }
                    };
                } else {
                    columnItemObj = {
                        ...obj[key],
                        showOverflowTooltip: true
                    };
                }
                arr.push(columnItemObj);
            }
        }
        // 不需要表格自定义
        return [
            {
                type: 'selection',
                width: 55,
                fixed: 'left',
                reserveSelection: true
            },
            ...arr
        ];
    }

    // 遍历对象找到自定义配置的信息，然后逐一合并
    const result = columns.map(columnItem => {
        if (tableOption[columnItem.field_key]) {
            Object.assign(columnItem, tableOption[columnItem.field_key]);
        }
        /**
         * 推广内容列自定义渲染
         */
        if (columnItem.field_key == 'promotion_content') {
            return {
                prop: columnItem.field_key,
                label: columnItem.field_name,
                minWidth: 170,
                ...tableOption[columnItem.field_key],
                render({ row }: any) {
                    const isEmptyValue = (value: any) => (['', null, undefined].includes(value) ? '--' : value);
                    return (
                        <ElTooltip
                            effect="dark"
                            placement="top"
                            show-after={800}
                            raw-content
                            content={row[columnItem.field_key]}
                            popper-class="auto_width auto_height">
                            <div class={bem('tooltip')} v-html={isEmptyValue(row[columnItem.field_key])}></div>
                        </ElTooltip>
                    );
                }
            };
        } else {
            return {
                prop: columnItem.field_key,
                showOverflowTooltip: true,
                label: columnItem.field_name,
                minWidth: 170,
                ...tableOption[columnItem.field_key]
            };
        }
    });
    return [
        {
            type: 'selection',
            width: 55,
            fixed: 'left',
            reserveSelection: true
        },
        ...result,
        {
            width: 46,
            fixed: 'right',
            label: (
                <div class="expand-header" onClick={() => handleExpandColumnsConfig()}>
                    <el-tooltip effect="dark" content="展示列设置" raw-content placement="top">
                        <img src={moreMenuSvg} />
                    </el-tooltip>
                </div>
            )
        }
    ];
};

// ======================== 表格 of end   ========================

// ======================== 表格配置列 of start   ========================

const columnConfigVisable = ref(false);
// 打开展开列弹窗
const handleExpandColumnsConfig = () => {
    columnConfigVisable.value = true;
};

const columnType = computed(() => {
    return {
        promotionLink: 9
    }[searchType.value];
});

const handleSortSubmit = async () => {
    isShowEmpty.value = true;
    await tableRef.value.reload();
    isShowEmpty.value = false;
};

// ======================== 表格配置列 of end   ========================

// ======================== 选择 of end   ========================
/** 多选选中的数量 */
const selectTableTotal = ref(0);
/**
 * 全选选中的数据数量
 */
const selectAllTotal = (value: number) => {
    selectTableTotal.value = value;
};
const onSelectAllChange = (val: never[]) => {
    exclude_ids.value = val;
};
const exclude_ids = ref([]);

const checkList = ref();

// 选中表格 checkbox
const onSelect = (selection: any, row: any) => {
    if (Array.isArray(selection)) checkList.value = selection.map(v => v.id);
};
// 全选
const onSelectAll = (selection: any) => {
    checkList.value = selection.map((v: { id: number }) => v.id);
};

// 导出
const handleExport = async (e: any) => {
    exportLoading.value = true;
    const params = {
        ...state.searchParams,
        select_type: tableRef.value?.getIsSelectAll() ? 2 : 1
    };
    // 选中的id
    const selectIds = tableRef.value?.getIsSelectAll() ? exclude_ids.value : checkList.value;
    const exportApi = {
        employee: {
            // 导出的异步任务接口
            api: exportPromotionAccount,
            // 导出的异步的选中的id字段
            key: 'ids'
        },
        product: {
            api: exportPromotionProduct,
            key: 'ids'
        },
        promotionLink: {
            api: exportStaticsPromotionUrl,
            key: 'ids'
        }
    }[searchType.value];
    try {
        await exportApi?.api({ ...params, [exportApi.key]: selectIds });
        parabolaAnimation(e);
        ShowTaskMessage('批量导出异步任务创建成功');
        tableRef.value?.clearSelection();
        tableRef.value?.clearAllSelect();
        exportLoading.value = false;
    } catch (err) {
        exportLoading.value = false;
    }
};

// ======================== 选择 of end   ========================

watch(
    () => props.type,
    val => {
        if (val) searchType.value = props.type;
        handleTabChange();
    }
);
</script>

<style lang="scss" scoped>
.employee_container {
    padding: 0 10px;

    :deep(.zw-search-form1) {
        padding: 0;
        padding-top: 4px;
        margin-bottom: 24px;
    }

    :deep(.el-table__inner-wrapper) {
        height: 500px;
    }
}

:deep(.expand-header) {
    cursor: pointer;
}
</style>
